package com.artconcurrency.chapter4;

/**
 * @ClassName com.artconcurrency.chapter4
 * Description:
 *
 * Main线程能够通过中断操作和cancel方法均可以使线程终止。
 * 这种通过标识位或中断操作的方式能够使线程在终止的时候有机会去清理资源，而不是武断的将线程停止，因此更优雅
 *
 * @Author tree
 * @Date 2019-05-01 23:16
 * @Version 1.0
 */
public class Shutdown {
    public static void main(String[] args) {
        Runner one = new Runner();
        Thread countthread = new Thread(one,"CountThread-interrupted");
        countthread.start();
        //睡眠1s，Main对count thread中断，使count thread能够感知中断而结束
        SleepUtils.second(1);
        countthread.interrupt();

        Runner two = new Runner();
        countthread = new Thread(two,"CountThread-cancelflag");
        countthread.start();
        //睡眠1s，Main对count thread中断，使count thread能够感知中断而结束
        SleepUtils.second(1);
        two.cancel();

    }

    static class Runner implements Runnable {
        private long i;
        private volatile boolean on = true;

        public void cancel(){
            on = false;
        }

        @Override
        public void run() {
            while (on && !Thread.currentThread().isInterrupted()){
                i++;
            }
            System.out.println(Thread.currentThread().getName()+" count i = "+i);

        }
    }

}


